var map;
var markers = [];
var index;
var contentString;
var infowindow;
var groupid;
var vehicleIDs;



function getSelectedGroup() {
	var e = document.getElementById("groupid_dropdwn");
	var selectedgroupID = e.options[e.selectedIndex].value;
	return selectedgroupID;
}

var vehiclepath = [ new google.maps.LatLng(12.095277, 76.555077),
            		new google.maps.LatLng(12.095280, 76.555177),
            		new google.maps.LatLng(12.095283, 76.555277),
            		new google.maps.LatLng(12.095283, 76.555377) ];

function initialize() {
	
	var contentString = 'vehicle';
	infowindow = new google.maps.InfoWindow({
		content : contentString
	});
	
	var mapOptions = {
			zoom : 16,
			center : vehiclepath[index],
			mapTypeId : google.maps.MapTypeId.ROADMAP
		};
	map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	$.getJSON('ajax/GetVehicleIDs.action?groupID=1', function(data) {
		vehicleIDs = data.vehicleIDs;
		for (var i = 0; i < vehicleIDs.length; i++) {
			markers.push(addBlankMarker());
		}		
	});
	
	setTimeout(trackgroup, 3000);

}

function addBlankMarker() {
	var newPoint = new google.maps.LatLng(0, 0);
	marker = new google.maps.Marker({
		position : newPoint,
		map : map,
		animation: google.maps.Animation.DROP
	});
	return marker;
}

function addMarker(location, index) {
	
}

function moveMarker(location, index) {
	markers[index].setPosition(location);
	map.panTo(location);
}
//
function trackgroup() {
	for (var i = 0; i < vehicleIDs.length; i++) {
		trackvehicle(vehicleIDs[i], i);
	}
	setTimeout(trackgroup, 3000);
}

//
function trackvehicle(vehicleid, index) {


	$.getJSON('ajax/GetVehiclePosition.action?vehicleID=' + vehicleid,
			function(data) {
				var lat = data.latitude;
				var lon = data.longitude;
				var time = data.time;
				var newPoint = new google.maps.LatLng(lat, lon);

				moveMarker(newPoint, index);
				infowindow.content = '<p>' + 'VehicleID:' + vehicleid + '</p>' + '<br>' +'<p>' + 'Time:' + time + '</p>';
				infowindow.open(map, markers[index]);
				map.panTo(newPoint);
			});

}
